<template>
    <div class="import_excel_form_container">
        <el-form ref="importForm" :model="formData" :rules="formRules" :label-width="labelWidth">
            <template v-for="(item, index) in formItems">
                <el-form-item :key="index" :ref="item.prop" v-if="filterFormItem(item)"
                              v-bind="getFormItemProps(item)">
                    <Widget v-model="formData[item.prop]" v-bind="getWidgetProps(item)"
                            :event="item.widget.event" :slots="item.widget.slots" />
                </el-form-item>
            </template>
            <el-form-item label="上传文件" style="margin-bottom: 0;">
                <el-upload class="import_upload upload-demo" ref="importUpload"
                           :class="{'manual_upload': !autoUpload}"
                           :action="fileApiUrl.uploadFile" :auto-upload="autoUpload"
                           :headers="headers" :show-file-list="false"
                           :data="{bizPath: 'temp', biz_type: 'import'}"
                           :limit="1" accept=".xls,.xlsx"
                           :before-upload="handleBeforeUpload"
                           :on-change="handleUploadChange"
                           :on-success="handleUploadSuccess">
                    <el-input type="text" v-model="optionData.fileName" placeholder="点击选择上传文件" readonly
                              @click.native="handleClickUpload" />
                </el-upload>
                <el-button class="submit_upload" type="success" @click="submitUpload"
                           v-if="!autoUpload">上传
                </el-button>
            </el-form-item>
            <el-form-item label="最后忽略行数" style="margin-bottom: 0;" v-if="false">
                <el-input type="text" v-model="optionData.lastRowSkipQty" placeholder="请输入最后忽略行数" />
            </el-form-item>
            <el-form-item style="margin-bottom: 0;" v-if="optionData.error">
                <span style="color: red;">{{ optionData.errorMsg || '' }}</span>
                <el-link type="danger" style="line-height: 1.5;" @click="handleDownloadError">请点击下载查看</el-link>
            </el-form-item>
            <el-form-item style="margin-bottom: 5px;" v-if="optionData.success">
                <span style="color: #67C23A;margin-right: 10px;">读取Excel成功，行数：{{ importData.list.length }}</span>
                <el-link type="primary" style="line-height: 1.5;" @click="handleShowImportList"
                         v-if="!showImportDetail && !optionData.uploadedShowData">查看数据
                </el-link>
            </el-form-item>
            <el-form-item style="margin-bottom: 5px;" v-if="optionData.import_error">
                        <span
                            style="color: red;margin-right: 10px;">导入失败：{{ optionData.import_msg }}</span>
            </el-form-item>
            <el-row v-if="optionData.success && (showImportDetail || optionData.uploadedShowData)">
                <el-col :span="24">
                    <vxeTableTemplate :data="importList" :options.sync="tableOptions" />
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script>
import fileApi from "@common/api/fileApi";
import poiApi from "@common/api/poiApi";
import {ElFormItem, genProps, widgetDefaultProps} from "@common/components/form/Dynamic/attributes";

export default {
    name: "ExcelForm",
    components: {
        Widget: () => import('@common/components/form/Dynamic/Widget.vue'),
    },
    props: {
        option: {
            type: Object,
            default: null,
        },
        autoUpload: {
            type: Boolean,
            default: true,
        },
        rules: {
            type: Object,
            default: null,
        },
        items: {
            type: Array,
            default: null,
        },
        labelWidth: {
            type: String,
            default: '110px',
        },
    },
    data() {
        const _this = this;
        return {
            excelContentType: [ 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ],
            fileApiUrl: fileApi.url,
            optionData: {},
            defaultOption: {
                fileName: '',
                success: false,
                error: false,
                errorMsg: '',
                errorFile: '',
                import_error: false,
                import_msg: '',
                lastRowSkipQty: 0,
                downloadFile: '', //下载模板名称 必填
                configFile: '',//导入模板配置名称 必填
                uploadedShowData: false,//读取成功后是否立即显示数据 默认false
                importBtnText: '导 入',//导入按钮文字
                closeBtnText: '关 闭',//关闭按钮文字
                disable_import_btn: true,
            },
            showImportDetail: false,
            importData: {},
            tableOptions: {
                ref: 'ShowImportDataTable',
                columns: [],
                pagination: false,
                hideIndex: true,
                getMaxHeight() {
                    return 450;
                },
            },
            importList: [],
            formData: {},
        };
    },
    computed: {
        headers() {
            return {
                token: this.$store.state.accessToken.token,
                account_set_sid: this.$utils.getAccountSetSid(),
            };
        },
        disableImportBtn() {
            return this.optionData.disable_import_btn;
        },
        formRules() {
            if (this.rules) {
                return this.rules;
            }
            return {};
        },
        formItems() {
            if (this.items) {
                return this.items;
            }
            return [];
        },
    },
    watch: {
        option: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        filterFormItem(item) {
            if (typeof item.filter === 'function') {
                return item.filter(item, this.formData);
            }
            return true;
        },
        getFormItemProps(item) {
            let props = genProps(ElFormItem, item);
            if (item.style) {
                props.style = item.style;
            }
            return props;
        },
        getWidgetProps(item) {
            let widgetProps = genProps(widgetDefaultProps, item.widget);
            if (item.widget.props) {
                let attributes = widgetProps.attributes || {};
                widgetProps.attributes = $.extend({}, attributes, item.widget.props);
            }
            return widgetProps;
        },
        init() {
            const _this = this;
            if (!_this.option) {
                return;
            }
            setTimeout(() => {
                _this.$nextTick(() => {
                    _this.$refs.importForm && _this.$refs.importForm.clearValidate();
                });
            }, 10);
            if (!this.$scopedSlots.content) {
                if (!this.$utils.isNotEmpty(this.option.configFile)) {
                    _this.$message.error('缺少配置：configFile');
                    return;
                }
            }
            _this.optionData = $.extend({}, _this.defaultOption, _this.option);
            _this.$emit('event', {
                type: 'disableImportBtn',
                value: _this.disableImportBtn,
            });
        },
        handleBeforeUpload(file) {
            let bol = true;
            if (this.excelContentType.indexOf(file.type) === -1) {
                this.$message.error('请选择Excel文件');
                return !bol;
            }
            this.$emit('event', {
                type: 'beforeUpload',
                file,
                callback(res) {
                    if (!res) {
                        bol = false;
                    }
                },
            });
            return bol;
        },
        handleUploadChange(file, fileList) {
            this.optionData = $.extend({}, this.optionData, {
                fileName: file.name,
            });
        },
        submitUpload() {
            this.$refs.importUpload.submit();
        },
        handleClickUpload() {
            this.$refs.importUpload.clearFiles();
        },
        handleUploadSuccess(res) {
            const _this = this;
            if (res.data) {
                poiApi.readExcel(res.data.sid, _this.optionData.configFile, _this.optionData.lastRowSkipQty).then(result => {
                    let resData = result.data || {};
                    _this.importData = $.extend({}, resData);
                    _this.optionData = $.extend({}, _this.optionData, {
                        success: true,
                        error: false,
                        import_error: false,
                        disable_import_btn: false,
                    });
                    _this.$emit('event', {
                        type: 'disableImportBtn',
                        value: _this.disableImportBtn,
                    });
                    _this.$emit('event', {
                        type: 'retData',
                        data: resData.list,
                    });
                    if (_this.showImportDetail || _this.optionData.uploadedShowData) {
                        _this.handleShowImportList();
                    }
                }).catch(err => {
                    _this.importData = $.extend({}, err);
                    _this.optionData = $.extend({}, _this.optionData, {
                        success: false,
                        error: true,
                        errorMsg: err.message,
                        errorFile: err.data,
                        list: [],
                    });
                    _this.importList = [];
                });
            }
        },
        handleDownloadError() {
            if (this.$utils.isNotEmpty(this.optionData.errorFile)) {
                let link = document.createElement('a');
                link.href = this.fileApiUrl.getFile + this.optionData.errorFile;
                link.download = this.optionData.downloadFile;
                link.click();
                document.body.removeChild(link);
            }
        },
        handleShowImportList() {
            let columns = this.importData.excelFileTitles.filter(item => {
                return item.hide === false;
            });
            columns = columns.map(item => {
                return {
                    label: item.title,
                    prop: item.fieldName,
                    align: 'center',
                };
            });
            this.tableOptions = $.extend({}, this.tableOptions, {
                columns,
            });
            this.importList = [].concat(this.importData.list || []);
            this.showImportDetail = true;
        },
        handleDownloadTemplate() {
            if (this.$utils.isNotEmpty(this.optionData.downloadFile)) {
                let link = document.createElement('a');
                link.href = poiApi.getDownloadUrl(this.optionData.downloadFile) + '?t=' + ((new Date()).getTime());
                link.download = this.optionData.downloadFile;
                link.click();
                document.body.removeChild(link);
            }
        },
        showErrorMsg(msg) {
            if (msg) {
                this.optionData = $.extend(this.optionData, {
                    import_error: true,
                    import_msg: msg,
                });
            } else {
                this.optionData = $.extend(this.optionData, {
                    import_error: false,
                    import_msg: '',
                });
            }
        },
        async confirm() {
            const _this = this;
            return await _this.validateForm('importForm');
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less">
.import_excel_form_container {
    .import_upload {
        display: inline-block;
        vertical-align: top;
        width: 100%;
        line-height: 1;

        .el-upload--text {
            width: 100%;
            height: auto;
            border: none;

            /deep/ .el-input__inner {
                cursor: pointer;
            }
        }
    }

    .manual_upload {
        width: calc(100% - 61px);
    }

    .submit_upload {
        display: inline-block;
        vertical-align: top;
    }
}
</style>
